package com.shopping.servlets;


import com.shopping.commons.LoginUtil;
import com.shopping.dao.UserDao;
import com.shopping.dao.impl.UserDaoImpl;
import com.shopping.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 处理步骤：
 * 1.获得客户端提交的数据
 * 2.调用底层处理类的处理方法进行功能处理
 * 3.根据处理结果进行页面跳转
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置request对象的编码集
        request.setCharacterEncoding("UTF-8");
        //获得客户端提交的用户名和密码
        String user_name = request.getParameter("user_name");
        String user_password = request.getParameter("user_password");

        //调用登陆方法
        UserDao userDao = new UserDaoImpl();
        User user = userDao.login(user_name, user_password);

        if (user == null) { //用户登陆失败
            response.setContentType("text/HTML;charset=utf-8");
            response.getWriter().write("<script>alert('用户名或密码错误请重新登录!');location.href='login.html';</script>");
            return;
        }

        //将当前用户对象存入session中
        HttpSession session = request.getSession();
        session.setAttribute("user", user);

        //获取当前所有cookie
        Cookie[] cookies = request.getCookies();

        //将未登录时的购物车信息添加到该用户的购物车中
        LoginUtil.addCacheCar(user.getUser_id(), cookies,response);

        //跳转到首页
        response.sendRedirect("/flower/flower.do?operate=queryFlower");
    }

}
